<template>
  <view class="container">
    <!-- 顶部状态栏 -->
    <view class="status-bar"></view>
    
    <!-- 页面内容 -->
    <view class="page-content">
      <!-- 标题区域 -->
      <view class="header">
        <text class="title">电费账单</text>
        <text class="subtitle">近12个月用电量与费用明细</text>
        <view class="header-actions">
          <view class="action-item" @tap="exportBills">
            <text class="action-icon">📤</text>
            <text class="action-text">导出</text>
          </view>
        </view>
      </view>
      
      <!-- 快速概览 -->
      <view class="quick-overview">
        <view class="overview-item primary">
          <text class="overview-icon">⚡</text>
          <view class="overview-content">
            <text class="overview-label">总用电量</text>
            <text class="overview-value">{{ totalUsage }}</text>
            <text class="overview-unit">kWh</text>
          </view>
        </view>
        
        <view class="overview-item secondary">
          <text class="overview-icon">💰</text>
          <view class="overview-content">
            <text class="overview-label">总电费</text>
            <text class="overview-value">{{ totalCost }}</text>
            <text class="overview-unit">元</text>
          </view>
        </view>
      </view>
      
      <!-- 统计卡片 -->
      <view class="stats-grid">
        <view class="stat-card">
          <text class="stat-label">平均月用电</text>
          <text class="stat-value">{{ averageMonthlyUsage }}</text>
          <text class="stat-unit">kWh</text>
          <view class="stat-trend" :class="getTrendClass(monthlyUsageTrend)">
            <text class="trend-icon">{{ monthlyUsageTrend >= 0 ? '↗' : '↘' }}</text>
            <text class="trend-value">{{ Math.abs(monthlyUsageTrend) }}%</text>
          </view>
        </view>
        
        <view class="stat-card">
          <text class="stat-label">平均月费用</text>
          <text class="stat-value">{{ averageMonthlyCost }}</text>
          <text class="stat-unit">元</text>
          <view class="stat-trend" :class="getTrendClass(monthlyCostTrend)">
            <text class="trend-icon">{{ monthlyCostTrend >= 0 ? '↗' : '↘' }}</text>
            <text class="trend-value">{{ Math.abs(monthlyCostTrend) }}%</text>
          </view>
        </view>
        
        <view class="stat-card">
          <text class="stat-label">最高月用电</text>
          <text class="stat-value">{{ maxUsage }}</text>
          <text class="stat-unit">kWh</text>
          <text class="stat-period">{{ maxUsageMonth }}</text>
        </view>
        
        <view class="stat-card">
          <text class="stat-label">最低月用电</text>
          <text class="stat-value">{{ minUsage }}</text>
          <text class="stat-unit">kWh</text>
          <text class="stat-period">{{ minUsageMonth }}</text>
        </view>
      </view>
      
      <!-- 图表区域 -->
      <view class="chart-section">
        <view class="section-header">
          <text class="section-title">用电趋势分析</text>
          <view class="chart-tabs">
            <text 
              v-for="tab in chartTabs" 
              :key="tab.value"
              class="tab-option"
              :class="{ 'tab-active': activeChartTab === tab.value }"
              @tap="switchChartTab(tab.value)"
            >
              {{ tab.label }}
            </text>
          </view>
        </view>
        
        <!-- 用电量图表 -->
        <view class="chart-card" v-if="activeChartTab === 'usage'">
          <view class="chart-header">
            <text class="chart-title">月度用电量趋势</text>
            <view class="chart-legend">
              <view class="legend-item">
                <view class="legend-color" style="background: #1890FF;"></view>
                <text class="legend-text">用电量</text>
              </view>
            </view>
          </view>
          
          <view class="chart-container">
            <qiun-data-charts 
              type="column"
              :chartData="usageChartData"
              :opts="usageChartOpts"
              canvasId="usageChart"
              :ontouch="true"
            />
          </view>
        </view>
        
        <!-- 费用图表 -->
        <view class="chart-card" v-if="activeChartTab === 'cost'">
          <view class="chart-header">
            <text class="chart-title">月度电费趋势</text>
            <view class="chart-legend">
              <view class="legend-item">
                <view class="legend-color" style="background: #52C41A;"></view>
                <text class="legend-text">电费</text>
              </view>
            </view>
          </view>
          
          <view class="chart-container">
            <qiun-data-charts 
              type="column"
              :chartData="costChartData"
              :opts="costChartOpts"
              canvasId="costChart"
              :ontouch="true"
            />
          </view>
        </view>
      </view>
      
      <!-- 账单明细 -->
      <view class="bill-details">
        <view class="section-header">
          <text class="section-title">账单明细</text>
          <view class="time-filter">
            <text class="filter-option" :class="{active: selectedPeriod === '12m'}" @tap="selectPeriod('12m')">12个月</text>
            <text class="filter-option" :class="{active: selectedPeriod === '6m'}" @tap="selectPeriod('6m')">6个月</text>
            <text class="filter-option" :class="{active: selectedPeriod === '3m'}" @tap="selectPeriod('3m')">3个月</text>
          </view>
        </view>
        
        <view class="bill-list-card">
          <view class="list-header">
            <text class="header-item month-col">月份</text>
            <text class="header-item usage-col">用电量</text>
            <text class="header-item price-col">单价</text>
            <text class="header-item cost-col">费用</text>
          </view>
          
          <scroll-view class="bill-list" scroll-y>
            <view 
              v-for="(bill, index) in filteredBillData" 
              :key="index"
              class="bill-item"
              :class="{ 
                'bill-item-highlight': bill.cost === maxCost || bill.usage === maxUsage,
                'bill-item-even': index % 2 === 0 
              }"
            >
              <view class="bill-month">
                <text class="month-text">{{ formatMonth(bill.month) }}</text>
                <text class="year-text">{{ getYear(bill.month) }}</text>
              </view>
              <view class="bill-usage">
                <text class="usage-value">{{ bill.usage }}</text>
                <text class="usage-unit">kWh</text>
              </view>
              <view class="bill-price">
                <text class="price-value">{{ bill.price }}</text>
                <text class="price-unit">元/kWh</text>
              </view>
              <view class="bill-cost">
                <text class="cost-value">{{ bill.cost }}</text>
                <text class="cost-unit">元</text>
                <view class="cost-badge" v-if="bill.cost === maxCost">
                  <text class="badge-text">最高</text>
                </view>
                <view class="cost-badge usage" v-else-if="bill.usage === maxUsage">
                  <text class="badge-text">最高</text>
                </view>
              </view>
            </view>
          </scroll-view>
          
          <view class="list-footer">
            <text class="footer-text">共 {{ filteredBillData.length }} 个月账单记录</text>
            <view class="footer-actions">
              <text class="footer-action" @tap="showAllBills" v-if="selectedPeriod !== '12m'">查看全部</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      activeChartTab: 'usage', // usage, cost
      selectedPeriod: '12m', // 12m, 6m, 3m
      chartTabs: [
        { label: "用电量", value: "usage" },
        { label: "电费", value: "cost" }
      ],
      
      // 账单概览数据
      totalUsage: "0",
      totalCost: "0",
      averageMonthlyUsage: "0",
      averageMonthlyCost: "0",
      monthlyUsageTrend: 2.5,
      monthlyCostTrend: 3.2,
      
      // 用电量图表数据
      usageChartData: {},
      usageChartOpts: {
        color: ["#1890FF"],
        padding: [15, 15, 0, 15],
        enableScroll: true,
        legend: {
          show: false
        },
        xAxis: {
          disableGrid: true,
          scrollShow: true,
          itemCount: 5,
          fontColor: "#666666",
          fontSize: 12
        },
        yAxis: {
          gridType: "dash",
          dashLength: 2,
          gridColor: "#F0F0F0",
          data: [{
            min: 0,
            max: 500
          }],
          format: (val) => {
            return val.toFixed(0) + "kWh"
          }
        },
        extra: {
          column: {
            type: "group",
            width: 20,
            categoryGap: 3,
            barBorderRadius: [6, 6, 6, 6]
          },
          tooltip: {
            showBox: true,
            showCategory: true,
            bgColor: "#FFFFFF",
            borderColor: "#E8E8E8",
            borderWidth: 1,
            textColor: "#333333"
          }
        }
      },
      
      // 费用图表数据
      costChartData: {},
      costChartOpts: {
        color: ["#52C41A"],
        padding: [15, 15, 0, 15],
        enableScroll: true,
        legend: {
          show: false
        },
        xAxis: {
          disableGrid: true,
          scrollShow: true,
          itemCount: 5,
          fontColor: "#666666",
          fontSize: 12
        },
        yAxis: {
          gridType: "dash",
          dashLength: 2,
          gridColor: "#F0F0F0",
          data: [{
            min: 0,
            max: 300
          }],
          format: (val) => {
            return val.toFixed(0) + "元"
          }
        },
        extra: {
          column: {
            type: "group",
            width: 20,
            categoryGap: 3,
            barBorderRadius: [6, 6, 6, 6]
          },
          tooltip: {
            showBox: true,
            showCategory: true,
            bgColor: "#FFFFFF",
            borderColor: "#E8E8E8",
            borderWidth: 1,
            textColor: "#333333"
          }
        }
      },
      
      // 账单明细数据
      billData: [],
      
      // 统计信息
      maxUsage: 0,
      minUsage: 0,
      maxUsageMonth: '',
      minUsageMonth: '',
      maxCost: 0,
      minCost: 0,
      maxCostMonth: '',
      minCostMonth: ''
    }
  },
  
  computed: {
    // 根据选择的时间段过滤账单数据
    filteredBillData() {
      const count = this.selectedPeriod === '12m' ? 12 : 
                   this.selectedPeriod === '6m' ? 6 : 3;
      return this.billData.slice(-count);
    }
  },
  
  methods: {
    // 切换图表选项卡
    switchChartTab(tab) {
      this.activeChartTab = tab;
    },
    
    // 选择时间段
    selectPeriod(period) {
      this.selectedPeriod = period;
    },
    
    // 显示全部账单
    showAllBills() {
      this.selectedPeriod = '12m';
    },
    
    // 获取趋势样式类
    getTrendClass(trend) {
      return trend >= 0 ? 'trend-up' : 'trend-down';
    },
    
    // 格式化月份显示
    formatMonth(monthStr) {
      const month = monthStr.split('-')[1];
      return `${month}月`;
    },
    
    // 获取年份
    getYear(monthStr) {
      return monthStr.split('-')[0];
    },
    
    // 生成模拟账单数据
    generateBillData() {
      const months = [];
      const currentDate = new Date();
      
      // 生成最近12个月的月份标签
      for (let i = 11; i >= 0; i--) {
        const date = new Date(currentDate);
        date.setMonth(currentDate.getMonth() - i);
        const monthStr = `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}`;
        months.push(monthStr);
      }
      
      // 生成模拟数据
      const usageData = [];
      const costData = [];
      const billDetails = [];
      
      let totalUsage = 0;
      let totalCost = 0;
      
      // 初始化极值
      this.maxUsage = 0;
      this.minUsage = Infinity;
      this.maxCost = 0;
      this.minCost = Infinity;
      
      months.forEach((month, index) => {
        // 模拟用电量数据 (150-450 kWh之间)，带季节性波动
        const seasonalFactor = 1 + 0.2 * Math.sin((index - 3) * Math.PI / 6);
        const usage = parseFloat((250 * seasonalFactor + Math.random() * 50).toFixed(1));
        
        // 模拟电价 (0.5-0.8元/kWh之间)
        const price = parseFloat((0.6 + Math.random() * 0.2).toFixed(2));
        
        // 计算费用
        const cost = parseFloat((usage * price).toFixed(2));
        
        usageData.push(usage);
        costData.push(cost);
        
        totalUsage += usage;
        totalCost += cost;
        
        // 更新极值
        if (usage > this.maxUsage) {
          this.maxUsage = usage;
          this.maxUsageMonth = month;
        }
        if (usage < this.minUsage) {
          this.minUsage = usage;
          this.minUsageMonth = month;
        }
        if (cost > this.maxCost) {
          this.maxCost = cost;
          this.maxCostMonth = month;
        }
        if (cost < this.minCost) {
          this.minCost = cost;
          this.minCostMonth = month;
        }
        
        billDetails.push({
          month: month,
          usage: usage,
          price: price,
          cost: cost
        });
      });
      
      // 更新概览数据
      this.totalUsage = totalUsage.toFixed(1);
      this.totalCost = totalCost.toFixed(2);
      this.averageMonthlyUsage = (totalUsage / 12).toFixed(1);
      this.averageMonthlyCost = (totalCost / 12).toFixed(2);
      
      // 更新图表数据
      this.usageChartData = {
        categories: months,
        series: [
          {
            name: "用电量",
            data: usageData,
            color: "#1890FF"
          }
        ]
      };
      
      this.costChartData = {
        categories: months,
        series: [
          {
            name: "电费",
            data: costData,
            color: "#52C41A"
          }
        ]
      };
      
      // 更新账单明细
      this.billData = billDetails;
    },
    
    // 导出账单
    exportBills() {
      uni.showActionSheet({
        itemList: ['导出为Excel', '导出为PDF', '分享账单'],
        success: (res) => {
          if (res.tapIndex === 0) {
            uni.showToast({
              title: 'Excel导出功能开发中',
              icon: 'none'
            });
          } else if (res.tapIndex === 1) {
            uni.showToast({
              title: 'PDF导出功能开发中',
              icon: 'none'
            });
          } else if (res.tapIndex === 2) {
            uni.showToast({
              title: '分享功能开发中',
              icon: 'none'
            });
          }
        }
      });
    }
  },
  
  onLoad() {
    // 页面加载时生成账单数据
    this.generateBillData();
  },
  
  onPullDownRefresh() {
    // 下拉刷新
    this.generateBillData();
    setTimeout(() => {
      uni.stopPullDownRefresh();
      uni.showToast({
        title: '数据已更新',
        icon: 'success',
        duration: 1500
      });
    }, 1000);
  }
}
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
}

.status-bar {
  height: var(--status-bar-height);
  background: transparent;
}

.page-content {
  flex: 1;
  padding: 30rpx 30rpx 140rpx;
}

/* 头部样式 */
.header {
  margin-bottom: 30rpx;
  position: relative;
}

.title {
  display: block;
  font-size: 46rpx;
  font-weight: 700;
  color: #1a1a1a;
  margin-bottom: 8rpx;
}

.subtitle {
  display: block;
  font-size: 26rpx;
  color: #666;
}

.header-actions {
  position: absolute;
  right: 0;
  top: 0;
}

.action-item {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  padding: 12rpx 20rpx;
  border-radius: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
}

.action-icon {
  font-size: 28rpx;
  margin-right: 8rpx;
}

.action-text {
  font-size: 24rpx;
  color: #1890ff;
  font-weight: 500;
}

/* 快速概览样式 */
.quick-overview {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.overview-item {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-radius: 20rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.08);
}

.overview-item.primary {
  background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
  color: white;
}

.overview-item.secondary {
  background: linear-gradient(135deg, #52c41a 0%, #389e0d 100%);
  color: white;
}

.overview-icon {
  font-size: 48rpx;
  margin-right: 20rpx;
}

.overview-content {
  flex: 1;
}

.overview-label {
  display: block;
  font-size: 24rpx;
  opacity: 0.9;
  margin-bottom: 8rpx;
}

.overview-value {
  display: block;
  font-size: 36rpx;
  font-weight: 700;
  margin-bottom: 4rpx;
}

.overview-unit {
  display: block;
  font-size: 22rpx;
  opacity: 0.8;
}

/* 统计网格样式 */
.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.stat-card {
  background: white;
  border-radius: 16rpx;
  padding: 25rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
}

.stat-label {
  display: block;
  font-size: 22rpx;
  color: #666;
  margin-bottom: 12rpx;
}

.stat-value {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  color: #1890ff;
  margin-bottom: 4rpx;
}

.stat-unit {
  display: block;
  font-size: 20rpx;
  color: #999;
  margin-bottom: 10rpx;
}

.stat-trend {
  display: flex;
  align-items: center;
  font-size: 20rpx;
}

.trend-up {
  color: #f5222d;
}

.trend-down {
  color: #52c41a;
}

.trend-icon {
  margin-right: 4rpx;
}

.stat-period {
  font-size: 20rpx;
  color: #999;
}

/* 图表区域样式 */
.chart-section {
  margin-bottom: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333;
}

.chart-tabs {
  display: flex;
  background: #f5f5f5;
  border-radius: 20rpx;
  padding: 4rpx;
}

.tab-option {
  padding: 12rpx 24rpx;
  font-size: 24rpx;
  color: #666;
  border-radius: 16rpx;
  transition: all 0.3s ease;
}

.tab-active {
  background: white;
  color: #1890ff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.chart-card {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.05);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.chart-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #333;
}

.chart-legend {
  display: flex;
}

.legend-item {
  display: flex;
  align-items: center;
  margin-left: 20rpx;
}

.legend-color {
  width: 20rpx;
  height: 20rpx;
  border-radius: 4rpx;
  margin-right: 8rpx;
}

.legend-text {
  font-size: 22rpx;
  color: #666;
}

.chart-container {
  width: 100%;
  height: 350rpx;
}

/* 账单明细样式 */
.bill-details {
  margin-bottom: 30rpx;
}

.time-filter {
  display: flex;
  background: #f5f5f5;
  border-radius: 20rpx;
  padding: 4rpx;
}

.filter-option {
  padding: 12rpx 20rpx;
  font-size: 22rpx;
  color: #666;
  border-radius: 16rpx;
  transition: all 0.3s ease;
}

.filter-option.active {
  background: white;
  color: #1890ff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.bill-list-card {
  background: white;
  border-radius: 20rpx;
  padding: 30rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.05);
}

.list-header {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
  margin-bottom: 10rpx;
  font-weight: 600;
  font-size: 24rpx;
  color: #333;
}

.header-item {
  text-align: center;
}

.month-col {
  flex: 1.5;
  text-align: left;
}

.usage-col {
  flex: 1;
}

.price-col {
  flex: 1;
}

.cost-col {
  flex: 1.2;
}

.bill-list {
  max-height: 600rpx;
  margin-bottom: 20rpx;
}

.bill-item {
  display: flex;
  align-items: center;
  padding: 24rpx 0;
  border-bottom: 1rpx solid #f8f8f8;
  transition: all 0.3s ease;
}

.bill-item-even {
  background-color: #fafafa;
}

.bill-item-highlight {
  background: linear-gradient(90deg, rgba(24, 144, 255, 0.05) 0%, rgba(24, 144, 255, 0.02) 100%);
  border-left: 4rpx solid #1890ff;
}

.bill-month {
  flex: 1.5;
  text-align: left;
}

.month-text {
  display: block;
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
  margin-bottom: 4rpx;
}

.year-text {
  display: block;
  font-size: 20rpx;
  color: #999;
}

.bill-usage {
  flex: 1;
  text-align: center;
}

.usage-value {
  display: block;
  font-size: 26rpx;
  color: #1890ff;
  font-weight: 500;
  margin-bottom: 2rpx;
}

.usage-unit {
  display: block;
  font-size: 20rpx;
  color: #999;
}

.bill-price {
  flex: 1;
  text-align: center;
}

.price-value {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 2rpx;
}

.price-unit {
  display: block;
  font-size: 20rpx;
  color: #999;
}

.bill-cost {
  flex: 1.2;
  text-align: center;
  position: relative;
}

.cost-value {
  display: block;
  font-size: 26rpx;
  color: #52c41a;
  font-weight: 600;
  margin-bottom: 2rpx;
}

.cost-unit {
  display: block;
  font-size: 20rpx;
  color: #999;
}

.cost-badge {
  position: absolute;
  top: -10rpx;
  right: 0;
  background: #ff4d4f;
  border-radius: 12rpx;
  padding: 4rpx 8rpx;
  font-size: 18rpx;
  color: white;
}

.cost-badge.usage {
  background: #1890ff;
}

.badge-text {
  font-size: 18rpx;
  font-weight: 500;
}

.list-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 20rpx;
  border-top: 1rpx solid #f0f0f0;
}

.footer-text {
  font-size: 22rpx;
  color: #999;
}

.footer-actions {
  display: flex;
}

.footer-action {
  font-size: 22rpx;
  color: #1890ff;
  padding: 8rpx 16rpx;
  background: rgba(24, 144, 255, 0.1);
  border-radius: 16rpx;
}
</style>